import React, { useEffect, useState, Key } from 'react'
import { useNavigate } from 'react-router-dom'
// 引入antd的样式
import { Button, Form, Input, Card, Table, Tooltip, message } from 'antd';
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons'
// 引入css的样式
import style from "./index.module.css"

//引入api中请求的方法
import {
  getHosSetListRequest,
  deleteList,
  BatchDeleteDataRequest
} from '@/api/hospital/hospitalSet';
// 引入接受的判别
import type {
  getHosSetListRecordsType,
  getHosSetListItemsType
} from '@api/hospital/model/hospitalSetTypes';
import type { searchHosFinishPraType } from './type'

export default function HospitalSet() {
  const navigate = useNavigate()
  //hospitalList是表单的数据
  const [hospitalList, setHospitalList] = useState<getHosSetListRecordsType>([]);
  //定义当前页码
  const [current, setCurrent] = useState(1)
  // 定义total(总个数)
  const [total, setTotal] = useState(0)
  // 定义pageSize(每页的数量)
  const [pageSize, setPageSize] = useState(15)
  //定义isLoading(table是否加载中)
  const [isLoading, setIsLoading] = useState(false);
  // 定义搜索内的状态
  const [fieldValue, setFieldValue] = useState<searchHosFinishPraType>({})
  // 定义删除的状态
  const [deleteReslut, setdeleteReslut] = useState(true)
  // 定义批量删除按钮的状态
  const [BatchDelete, setBatchDelete] = useState(true)
  // 定义保存批量删除idList中使用
  const [someIdList, setSomeIdList] = useState<Key[]>([])
  // 初始化时获取数据
  useEffect(() => {
    setIsLoading(true)
    //封装一个请求函数才可以,记得后续调用
    const getHosSetList = async () => {
      const result = await getHosSetListRequest({
        // 页数
        page: current,
        // 限制查询的数量
        limit: pageSize,
        ...fieldValue
      });
      // 修改data
      setHospitalList(result.records)
      //数据的总长度设置给state
      setTotal(result.total)
      //请求完成后要把isLoading修改为false 
      setIsLoading(false)
    }
    getHosSetList();
  }, [current, pageSize, fieldValue, deleteReslut])
  // 删除事件
  const deleteDate = (id: string) => {
    return async () => {
      await deleteList(id)
      setdeleteReslut(!deleteReslut)
      message.success('删除成功')
    }
  }
  // 批量删除事件
  const BatchDeleteData = async () => {
    await BatchDeleteDataRequest(someIdList)
    message.success('删除成功')
    setBatchDelete(true)
    // 控制状态让他重新渲染
    setdeleteReslut(!deleteReslut)
  }

  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',

    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',

    },
    {
      title: '签名',
      dataIndex: 'signKey',
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
    },
    {
      title: '联系人手机',
      dataIndex: 'contactsPhone',
    },
    {
      title: '操作',
      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any, data: getHosSetListItemsType) {
        // 获取id
        const { id } = data
        return (
          <div>
            <Tooltip title='修改医院' color={'green'}>
              <Button
                type='primary' icon={<EditOutlined />}
                className={style.mr}
                // 添加修改点击事件  通过param传参将id传过去
                onClick={() => { navigate(`/syt/hospital/upDataResult/${id}`) }}
              ></Button>
            </Tooltip>
            <Tooltip title='删除医院' color={'red'}>
              <Button type='primary' danger
                icon={<DeleteOutlined />}
                onClick={deleteDate(id)}>
              </Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];
  return (
    <div>
      <Card>
        {/* 添加一个提交事件 */}
        <Form name="basic" wrapperCol={{ span: 30 }} layout="inline"
          onFinish={(fieldValue: searchHosFinishPraType) => {
            setFieldValue(fieldValue)
          }}>
          <Form.Item name="hosname" >
            <Input placeholder='医院名称' />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder='医院编号' />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.mt}>
          {/* 添加事件 */}
          <Button type='primary'
            className={style.mr}
            onClick={() => { navigate('/syt/hospital/addResult') }}>添加</Button>
          {/* 删除事件 */}
          <Button type='primary' danger disabled={BatchDelete} onClick={BatchDeleteData}>批量删除</Button>
        </div>
        <Table
          className={style.mt}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
           // 控制多选框
          rowSelection={{
            onChange(idList: Key[]) {
              console.log(idList);
              if (idList) {
                setBatchDelete(!idList.length)
                setSomeIdList(idList)
              }
            }
          }}
          pagination={{
            //页码的配置：当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5],
            // 点击修改当前获取的页数和显示页数
            onChange(page, pageSize) {
              setPageSize(pageSize)
              setCurrent(page)
            },
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            // 所有的数据
            showTotal(total) {
              return `总共有${total}条数据`
            }
          }}
        />
      </Card >
    </div >
  )
}

